package com.ihd.ihardware.view.enter.view;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.ihd.ihardware.R;
import com.ihd.ihardware.app.MyApplication;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivitySplash0Binding;
import com.ihd.ihardware.pojo.BannerRes;
import com.ihd.ihardware.pojo.MembersRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.view.enter.viewModel.SplashViewModel;
import com.ihd.ihardware.view.tzc.discovery.view.BaseWebActivity;
import com.ihd.ihardware.view.tzc.main.view.BalanceActivity;
import com.ihd.ihardware.view.tzc.me.view.PerInfoActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.File;

import cn.wowjoy.commonlibrary.app.Constans;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.HttpUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;

public class SplashActivity0 extends BaseActivity<ActivitySplash0Binding, SplashViewModel> {

    private int REQUEST_CODE_BLUETOOTH_ON = 100;
    private CountDownTimer cdt;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();

        if (!isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }

        setRx(AppConstans.INFO, new BaseConsumer<UserInfoRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(UserInfoRes mLiveData) {
                MyApplication.memberId = new MembersRes.DataBean();
                MyApplication.memberId.setMemberId("");

                if (TextUtils.isEmpty(mLiveData.getData().getWeight())) {
                    Intent mIntent = new Intent(SplashActivity0.this, PerInfoActivity.class);
                    mIntent.putExtra("userinfo", mLiveData.getData());
                    startActivity(mIntent);
                } else {
                    SPUtils.putString(AppConstans.USER_INFO, new Gson().toJson(mLiveData.getData(), UserInfoRes.DataBean.class));
                    Intent mIntent = new Intent(SplashActivity0.this, BalanceActivity.class);
                    startActivity(mIntent);
                }
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(SplashActivity0.this, error.getMessage());
            }
        });

        setRx(AppConstans.BANNER, new BaseConsumer<BannerRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(BannerRes mLiveData) {
                if (mLiveData.getData() != null && mLiveData.getData().size() > 0) {
                    Glide.with(SplashActivity0.this)
                            .load(mLiveData.getData().get(0).getImageUrl())
                            .into(binding.bannerImg);
                    if (!TextUtils.isEmpty(mLiveData.getData().get(0).getUrl()))
                        binding.bannerImg.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent i = new Intent(SplashActivity0.this, BaseWebActivity.class);
                                i.putExtra("url", mLiveData.getData().get(0).getUrl());
                                startActivity(i);
                            }
                        });
                }
                AndPermission.with(SplashActivity0.this)
                        .runtime()
                        .permission(
//                                Permission.READ_PHONE_STATE,
                                Permission.READ_EXTERNAL_STORAGE,
                                Permission.WRITE_EXTERNAL_STORAGE,
                                Permission.CAMERA,
                                Permission.ACCESS_FINE_LOCATION,
                                Permission.ACCESS_COARSE_LOCATION,
                                Permission.RECORD_AUDIO
                        )
                        .onGranted(permissions -> {
                            File f = new File(AppConstans.BASE_PATH);
                            if (!f.exists())
                                f.mkdirs();
                            if (!BLEUtils.getInstance().isBluetoothOpened()) {
                                Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON);
                            }
                            if (mLiveData.getData() != null && mLiveData.getData().size() > 0) {
                                cdt = new CountDownTimer(mLiveData.getData().get(0).getPlayTime() * 1000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        binding.countTV.setText(millisUntilFinished / 1000 + " 跳过");
                                    }

                                    @Override
                                    public void onFinish() {
                                        connectBluetooth();
                                    }
                                };
                            } else {
                                cdt = new CountDownTimer(4000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        binding.countTV.setText(millisUntilFinished / 1000 + " 跳过");
                                    }

                                    @Override
                                    public void onFinish() {
                                        connectBluetooth();
                                    }
                                };
                            }
                            cdt.start();
                        })
                        .onDenied(permissions -> {
                            finish();
                        })
                        .start();
            }

            @Override
            protected void onError(Throwable error) {
                AndPermission.with(SplashActivity0.this)
                        .runtime()
                        .permission(
//                                Permission.READ_PHONE_STATE,
                                Permission.READ_EXTERNAL_STORAGE,
                                Permission.WRITE_EXTERNAL_STORAGE,
                                Permission.CAMERA,
                                Permission.ACCESS_FINE_LOCATION,
                                Permission.ACCESS_COARSE_LOCATION,
                                Permission.RECORD_AUDIO
                        )
                        .onGranted(permissions -> {
                            File f = new File(AppConstans.BASE_PATH);
                            if (!f.exists())
                                f.mkdirs();
                            if (!BLEUtils.getInstance().isBluetoothOpened()) {
                                Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON);
                            }
                            cdt = new CountDownTimer(3000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    binding.countTV.setText(millisUntilFinished / 1000 + " 跳过");
                                }

                                @Override
                                public void onFinish() {
                                    connectBluetooth();
                                }
                            };
                            cdt.start();
                        })
                        .onDenied(permissions -> {
                            finish();
                        })
                        .start();
            }
        });

        viewModel.getBanner();

        binding.countTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cdt != null)
                    cdt.cancel();
                connectBluetooth();
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (cdt != null)
            cdt.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (cdt != null)
            cdt.cancel();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    cdt.start();
                    break;
                case Activity.RESULT_CANCELED:
                    ToastUtils.showLong(this, "请手动打开蓝牙进入app，才能获取测量数据哦~");
                    cdt.start();
                    break;
                default:
                    break;
            }
        }
    }

    private void connectBluetooth() {
        if (TextUtils.isEmpty(SPUtils.getString(Constans.GATEWAY_TOKEN, ""))) {
            Intent i = new Intent(SplashActivity0.this, PerActivity.class);
            startActivity(i);
            finish();
        } else {
            if (HttpUtils.getInstance().isNetworkConnected())
                viewModel.getUserInfo();
            else {
                if (!TextUtils.isEmpty(SPUtils.getString(AppConstans.USER_INFO, ""))) {
                    Intent mIntent = new Intent(SplashActivity0.this, BalanceActivity.class);
                    startActivity(mIntent);
                } else {
                    Intent i = new Intent(SplashActivity0.this, PerActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash0;
    }

    @Override
    protected Class getViewModelClass() {
        return SplashViewModel.class;
    }

}
